package vh.sphynx.net.core;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import vh.sphynx.runtime.ExecutionContext;
import vh.sphynx.runtime.SphynxInterpreter;
import vh.sphynx.sphynx.XFeatureCall;
import vh.sphynx.sphynx.XFunctionDeclaration;
import vh.sphynx.util.SphynxRuntimeUtil;

public class SphynxScriptNameResolver extends UrlCacheResolver {
	private XFunctionDeclaration function;
	private ExecutionContext context;
	private SphynxInterpreter interpreter; 
	
	public SphynxScriptNameResolver(SphynxInterpreter interpreter, ExecutionContext context, XFunctionDeclaration func) {
		this.context = context;
		this.function = func;
		this.interpreter = interpreter;
	}
	
	public static SphynxScriptNameResolver createNameResolver(SphynxInterpreter interpreter, ExecutionContext context, XFunctionDeclaration func) {
		return new SphynxScriptNameResolver(interpreter, context, func);
	}
	
	@Override
	public String resolveCacheName(URL query) {		
		Object resolvedName = null;
		
		try {
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("input", query.toString());
			XFeatureCall call = SphynxRuntimeUtil.createFeatureCall(function, args);
			resolvedName = interpreter.evaluate(call, context);
		}
		catch (RuntimeException e) {}
		
		return resolvedName != null ? resolvedName.toString() : null;
	}
}
